import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { HivePlusResolver } from 'hive-unplugin-vue-components/resolvers';
import Components from 'hive-unplugin-vue-components/vite';
import AutoImport from 'unplugin-auto-import/vite';
import vueSetupExtend from 'vite-plugin-vue-setup-extend';

import { configCompressPlugin } from './compress';
import { configEslintPlugin } from './eslint';
import { configHtmlPlugin } from './html';
import { configSvgIconsPlugin } from './svg-icons';
import { configVisualizerPlugin } from './visualizer';

type ConfigOptions = {
  iconDirs: string[];
  customDomId: string;
  viteVisualizer: boolean;
};

export const createVitePlugins = (env: any, options: ConfigOptions) => {
  const { VITE_APP_NODE_ENV: appEnv, NODE_ENV: nodeEnv } = env;
  const isProduction = nodeEnv === 'production';

  const vitePlugins: any[] = [
    vue(),
    vueSetupExtend(),
    vueJsx(),
    AutoImport({
      resolvers: [
        HivePlusResolver({
          importStyle: 'sass',
        })
      ],
    }),
    Components({
      // allow auto load markdown components under `./src/components/`
      extensions: ['vue', 'md'],
      // allow auto import and register components used in markdown
      include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
      resolvers: [
        HivePlusResolver({
          importStyle: 'sass',
        })
      ],
      dts: 'src/components.d.ts',
    }),
  ];

  if (isProduction) {
    // 配置压缩插件
    vitePlugins.push(configCompressPlugin(env));
  }

  // 配置 svg 图标插件
  vitePlugins.push(configSvgIconsPlugin(options.iconDirs, options.customDomId));

  if (!isProduction) {
    // 配置 eslint 插件
    vitePlugins.push(configEslintPlugin());
  }

  if (isProduction && options.viteVisualizer) {
    // 配置 visualizer 插件
    vitePlugins.push(configVisualizerPlugin());
  }

  // 配置注入html
  vitePlugins.push(configHtmlPlugin(env));

  // eslint-disable-next-line no-console
  console.log(`.env.${appEnv || ''} 文件已启动，vite plugins 配置完成`);

  return vitePlugins;
};
